import symbol from 'log-symbols';
import chalk from 'chalk';
import inquirer from "inquirer";
const path = require('path');
import fs from 'fs';
import {
    notExistFold,
    addSites
} from './util';

// 询问用户运行项目
let newPromptList = [
    {
        type: 'input',
        name: 'siteName',
        message: '请输入新站点的名字：'
    },
];

let newPrompt = () => {
    return new Promise(resolve => {
        inquirer
            .prompt(newPromptList)
            .then(answer => {
                resolve(answer);
            })
    });
}

let Add = async () => {
    const site = await newPrompt();
    const siteName = site.siteName;

    // 站点名不能为空
    if (siteName.length === 0) {
        console.log(symbol.error, chalk.greenBright('新建站点的时候，请输入站点名'));
    } else {
        // 如果文件名不存在则继续执行,否则退出
        await notExistFold(path.resolve('sites') + `/${siteName}`);

        console.log(chalk.blueBright('开始创建新站点目录'));

        try {
            const isHave = await notExistFold(path.resolve('sites'), true);
            if (isHave !== true) {
                const answer = await new Promise(resolve => {
                    inquirer
                        .prompt([{
                            type: 'list',
                            name: 'warning',
                            message: '当前项目为单站点模式，是否确认转换为多站点（转换后无法对src内pug进行打包）',
                            choices: ['yes', 'no']
                        }])
                        .then(answer => {
                            resolve(answer.warning);
                        })
                });
                if (answer === 'yes') {
                    fs.mkdirSync(path.resolve('sites'));
                } else {
                    return ;
                }
            }

            addSites(siteName);

            console.log(chalk.blueBright('新建站点成功!'));
        } catch ( e ) {
            console.log(symbol.error, chalk.greenBright('新建目录失败，请手动检测问题'));
        }
    }
};

module.exports = Add;
